package com.mall.order.services;

import com.mall.order.OrderCancelService;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.entitys.Stock;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.StockMapper;
import com.mall.order.dto.CancelOrderRequest;
import com.mall.order.dto.CancelOrderResponse;
import com.mall.user.constants.SysRetCodeConstants;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class OrderCancelServiceImpl implements OrderCancelService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private StockMapper stockMapper;

    /**
     * 取消订单
     * @param request
     * @return
     */
    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();
        request.requestCheck();
        try {
            //修改订单状态和交易关闭时间
            Order order = new Order();
            order.setOrderId(request.getOrderId());
            order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            order.setUpdateTime(new Date());
            order.setCloseTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
            //查找订单对应商品id和商品数量
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(request.getOrderId());
            for (OrderItem orderItem : orderItems) {
                //修改库存和冻结库存
                Long itemId = orderItem.getItemId();
                Integer num = orderItem.getNum();
                Stock stock = new Stock();
                stock.setItemId(itemId);
                stock.setStockCount(num.longValue());//库存增加
                stock.setLockCount(-num);//冻结库存减少
                stockMapper.updateStock(stock);
            }
        }catch (Exception e){
            response.setCode(SysRetCodeConstants.DB_EXCEPTION.getCode());
            response.setMsg(SysRetCodeConstants.DB_EXCEPTION.getMessage());
            return response;
        }
        response.setCode(SysRetCodeConstants.SUCCESS.getCode());
        response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return response;
    }
}
